package _3TCPChat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class ChatClient 
{
	// 服务器地址
	String host = "127.0.0.1";
	// 服务器端口
	int port= 8888;
	
	// 聊天窗口对象
	ChatClientFrame f;
	
	// 套接字
	Socket s;
	
	// 发送信息
	public void send(String text)
	{

		try {
			// 得到输出流			
			OutputStream out = s.getOutputStream();
			// 发送内容
			out.write(text.getBytes());
		} catch (IOException e) 
		{
			f.showMsg("出错了:"+e.getMessage());
		}
	}
	
	// 连接服务器
	public void connect()
	{
		// 开启一个子线程,在子线程中连接服务器,不卡住界面
		Thread t = new Thread(new Runnable() {
			
			@Override
			public void run() {
				f.showMsg("连接"+host+":"+port);
				try {
					s = new Socket(host,port);
				} catch (UnknownHostException e) {
					f.showMsg("出错了"+e.getMessage());
					return;
				} catch (IOException e) {
					f.showMsg("出错了"+e.getMessage());
					return;
				}		
				f.showMsg("连接成功");
				
				
				// 读取数据
				// 从socket得到输入流
				InputStream in=null;
				try {
					in = s.getInputStream();
				} catch (IOException e1) {
					return;
				}
				while (true) {
					
					// 读取数据
					byte[] buf = new byte[1024];
					int len;
					try {
						len = in.read(buf);
						if (len == -1) 
						{
							f.showMsg("读到长度-1");
							break;
						}
						// 
						String str = new String(buf, 0, len);
						f.showMsg(str);
						
						
					} catch (IOException e) {
						f.showMsg("出错了或服务器断开了:"+e.getMessage());
						break;
					}
				}

				
				
			}
		});
		t.start();
		
	}

}
